<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    :ok-button-props="{ props: { disabled: disableSubmit } }"
    cancelText="关闭">
    <template slot="footer">
      <a-button @click="handleCancel">关闭</a-button>
      <a-button v-if="!disableSubmit" type="primary" @click="handleOk" :loading="buttonok">确定</a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row>

          <a-col :span="24">
            <a-form-item label="标题" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input :disabled="disableSubmit" v-decorator="['title', validatorRules.title]"
                       placeholder="请输入标题"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="培训日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date :disabled="disableSubmit" placeholder="请选择培训日期"
                      v-decorator="['trainDate', validatorRules.trainDate]" :trigger-change="true" 
                      style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="培训内容" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-textarea :disabled="disableSubmit" v-decorator="['content', validatorRules.content]" rows="4"
                          placeholder="请输入培训内容"/>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-textarea :disabled="disableSubmit" v-decorator="['remark']" rows="4" placeholder="请输入备注"/>
            </a-form-item>
          </a-col>
          <a-col :span="24" v-if="disableSubmit">
            <div id="qrcode" ref="qrcode" style="margin-left: 21%;"></div>
            <a-button type="primary" @click="hanleDown" style="margin-left: 21%;margin-top:10px;">二维码下载</a-button>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
  </j-modal>
</template>

<script>

  import QRCode from 'qrcodejs2'
  import pick from 'lodash.pick'
  import {validateDuplicateValue} from '@/utils/util'
  import JDate from '@/components/jeecg/JDate'
  import { httpAction, postAction, getAction } from '@/api/manage'

  export default {
    name: "HrCourseModal",
    components: {
      JDate,
    },
    data () {
      return {
        qrcode: '',
        form: this.$form.createForm(this),
        title: "操作",
        width: 800,
        visible: false,
        buttonok: false,
        model: {},
        labelCol: {
          xs: {span: 24},
          sm: {span: 5},
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 16},
        },
        confirmLoading: false,
        disableSubmit: false,
        validatorRules: {
          title: {
            rules: [
              {required: true, message: '请输入标题!'},
            ]
          },
          content: {
            rules: [
              {required: true, message: '请输入培训内容!'},
            ]
          },
          trainDate: {
            rules: [
              {required: true, message: '请输入培训日期!'},
            ]
          },
        },
        url: {
          add: "/online/api/createHrCourse",
          edit: "/online/api/updateHrCourse",
          get: "/online/api/getHrCourse",
        }
      }
    },
    created () {
    },
    watch: {
      visible (newVisible) {
        if(this.disableSubmit){
          if (newVisible) {
            this.$nextTick(function () {
              this.init()
            })
          }
        }
      }
    },
    methods: {
      async init () {
        const res = await postAction('/online/api/getWxTypeInfo', {});
        let wxInfo = {};
        if(res.code ==0){
          wxInfo = res.result;
        }
        let appid = wxInfo.appid;
        // 为了防止重复生成二维码，使用置空进行控制
        document.getElementById('qrcode').innerHTML = ''
        // 设置二维码内容  显示内容(text所指向内容)必须是UTF-8编码格式。
        const content = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri=http://eim.kejicloud.com/sysServer/online/trainInfo&response_type=code&scope=snsapi_base&state="+this.model.id+"#wechat_redirect";
        this.qrcode = new QRCode('qrcode', {
          width: 260,
          height: 260,
          colorDark: '#000',
          colorLight: '#fff',
          correctLevel: QRCode.CorrectLevel.L, // 容错率，L/M/H
          text: content
        })
      },
      // 下载二维码
      hanleDown () {
        const imgs = document.getElementById('qrcode').getElementsByTagName('img')
        const a = document.createElement('a')
        a.download = this.model.title+'二维码'
        a.href = imgs[0].src
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
      },

      add () {
        this.edit({});
      },
      async edit (record) {
        this.form.resetFields();
        this.visible = true;
		    this.model = {};
        if (record.id) {
          httpAction(this.url.get, {id: record.id}, "post").then((res) => {
            if (res.success) {
              this.model = Object.assign({}, res.result);
              this.visible = true;
              this.$nextTick(() => {
                this.form.setFieldsValue(pick(this.model, 'title', 'content', 'trainDate', 'remark'))
              })
            }
          })
        }
      },
      close () {
        this.$emit('close');
        this.visible = false;
      },
      handleOk () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            that.buttonok = true
            let httpurl = '';
            let method = '';
            if (!this.model.id) {
              httpurl += this.url.add;
              method = 'post';
            } else {
              httpurl += this.url.edit;
              method = 'put';
            }
            let formData = Object.assign(this.model, values);
            console.log("表单提交数据", formData)
            httpAction(httpurl, formData, method).then((res) => {
              if (res.success) {
                that.$message.success('提交成功!');
                that.$emit('ok');
              } else {
                that.$message.warning(res.message);
              }
              setTimeout(() => { that.buttonok = false; }, 500);
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })
          }

        })
      },
      handleCancel () {
        this.close()
      },
      popupCallback(row){
        this.form.setFieldsValue(pick(row, 'title', 'content', 'trainDate', 'remark'))
      },


    }
  }
</script>
